% Matlab Code for replication of "Optimal Debt Maturity and Firm Investment"
% by J. Jungherr and I. Schott, September 2020
% Solve period T-1

for zz = 1:lenz
    for bb = 1:lenb  
        
        % Define firm-level state
        S.DEBT  = PARMS.DEBT{zz}(bb);
        S.zz    = zz;
        
        % Create initial guess and bounds (These bounds should not bind after convergence of the solution!)
        firm_problem_initial_guess
        
        % SOLVE THE FIRM PROBLEM
        [optimum, ~, exitflag] ...
            = fminsearchbnd(@(x) firm_optim_final(x,S,PARMS),opt_ini,lb,ub);
        
        % Obtain remaining variables at optimum
        [~, eq_out] = firm_optim_final(optimum,S,PARMS,1);
                
        % Save policy functions 
        compute_policy_functions
        
    end % End of B loop
end % End of Z loop

save_history % saves all policies in HISTORY cell

VAL.period = VAL.period + 1;

% Interpolate policy functions
build_interpol_functions
